<template>
  <div class="order-history-container">
    <!-- 桌面端表格 -->
    <div class="desktop-view">
      <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索订单号"
          class="search-input"
        />
        <el-select
          v-model="filterStatus"
          class="status-select"
        >
          <el-option value="">全部状态</el-option>
          <el-option
            v-for="status in statusOptions"
            :key="status"
            :value="status"
          >
            {{ status }}
          </el-option>
        </el-select>
      </div>

      <el-table
        :data="filteredOrders"
        style="width: 100%"
        stripe
        v-loading="loading"
        @row-click="toggleRowExpansion"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-card
              class="order-details"
              style="width:20%"
            >
              <h3>订单详情</h3>
              <div class="items-list">
                <div
                  v-for="(item, index) in row.cpItems"
                  :key="index"
                  class="card-header"
                >
                  <span class="item-name">{{ item.CD_INFO.NAME }}</span>
                  <span class="item-quantity">×{{ item.CD_INFO.quantity }}</span>
                  <span class="item-price">¥{{ (item.CD_INFO.PRICE * item.CD_INFO.quantity).toFixed(2) }}</span>
                </div>
                <el-divider />
                <div class="card-header">
                  <span class="item-name">总价</span>
                  <span class="item-quantity">{{ '' }}</span>
                  <span class="item-price">¥{{ row.TOTAL.toFixed(2) }}</span>
                </div>
              </div>
            </el-card>
          </template>
        </el-table-column>

        <el-table-column
          prop="orderNumber"
          label="订单号"
          sortable
        />
        <el-table-column
          prop="YY_TIME"
          label="预约取货日期"
          sortable
        />

        <el-table-column
          label="状态"
          width="120"
        >
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.STATE)">
              {{ row.STATE }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="total"
          label="总金额"
          width="120"
        >
          <template #default="{ row }">
            ¥{{ row.TOTAL.toFixed(2) }}
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <div v-if="['13566511216'].includes(WORKID)">
              <el-button
                type="success"
                size="small"
                circle
                @click.stop="handleComfirm(row)"
                v-if="row.STATE == '待确认'"
              >
                <el-icon>
                  <Download />
                </el-icon>
              </el-button>

              <el-button
                type="success"
                size="small"
                circle
                @click.stop="handleComfirm(row)"
                v-if="row.STATE == '已确认'"
              >
                <el-icon>
                  <Finished />
                </el-icon>
              </el-button>

              <el-popconfirm
                :title="`订单 ${row.STATE}，确定退回吗?`"
                @confirm="handleDelete(row)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    circle
                    v-show="['待确认'].includes(row.STATE)"
                  >
                    <el-icon>
                      <DArrowLeft />
                    </el-icon>
                  </el-button>
                </template>
              </el-popconfirm>

            </div>
            <div v-if="[WORKID].includes(row.WORKID)">
              <el-button
                type="danger"
                size="small"
                circle
                @click.stop="handleDelete(row)"
                v-if="row.STATE == '待确认'"
              >
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- <table class="order-table">
        <thead>
          <tr>
            <th @click="sortBy('orderNumber')">订单号</th>
            <th @click="sortBy('date')">日期</th>
            <th>状态</th>
            <th @click="sortBy('total')">总金额</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="order in paginatedOrders"
            :key="order.orderNumber"
          >
            <td>{{ order.orderNumber }}</td>
            <td>{{ order.date }}</td>
            <td>
              <span :class="['status-tag', statusClass(order.status)]">
                {{ order.status }}
              </span>
            </td>
            <td>¥{{ order.total.toFixed(2) }}</td>
            <td>
              <button
                class="detail-btn"
                @click="toggleDetails(order.orderNumber)"
              >
                {{ expandedOrder === order.orderNumber ? '收起' : '详情' }}
              </button>
              <button
                class="delete-btn"
                @click="handleDelete(order)"
                :disabled="order.status === '已完成'"
              >
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table> -->

      <!-- <div
        class="pagination"
        style="margin-top: 10px;"
      >
        <button
          v-for="page in totalPages"
          :key="page"
          @click="currentPage = page"
          :class="{ active: currentPage === page }"
        >
          {{ page }}
        </button>
      </div> -->
    </div>

    <!-- 移动端卡片 -->
    <div class="mobile-view">
      <div class="mobile-filter">
        <el-input
          v-model="searchQuery"
          placeholder="搜索订单"
          class="mobile-search"
        />
        <el-select
          v-model="filterStatus"
          class="mobile-status"
        >
          <el-option value="">全部状态</el-option>
          <el-option
            v-for="status in statusOptions"
            :key="status"
            :value="status"
          >
            {{ status }}
          </el-option>
        </el-select>
      </div>

      <div class="order-cards">
        <el-card
          v-for="order in paginatedOrders"
          :key="order.orderNumber"
          class="order-card"
          :style="{ backgroundColor: newCD_RECORD_ID == order.CD_RECORD_ID ? 'rgb(239.8, 248.9, 235.3)':'' }"
        >
          <div class="card-header">
            <!-- <div class="order-number">{{ order.WORKID }}</div> -->
            <div>
              <div style="text-align:left">
                订单号:
              </div>
              <div
                class="order-number"
                style="text-align:left"
              >{{ order.orderNumber }}</div>
              <!-- <div class="order-number">工号:{{ order.WORKID }}</div> -->
            </div>
            <el-tag :type="statusTagType(order.STATE)">
              {{ order.STATE }}
            </el-tag>
          </div>

          <div class="card-body">
            <div class="info-row">
              <span>取货日期：</span>
              {{ order.YY_TIME }}
            </div>
            <div class="info-row">
              <span>总价：</span>
              ¥{{ order.TOTAL.toFixed(2) }}
            </div>

            <div
              v-show="expandedOrder === order.orderNumber"
              class="details"
            >

              <div class="card-header">
                <div
                  class="item-name"
                  style="width: 100px;text-align: left;"
                >菜品</div>
                <div
                  class="item-name"
                  style="width: 80px;text-align: left;"
                >数量</div>
                <div
                  class="item-name"
                  style="width: 80px;text-align: right;"
                >小计</div>
              </div>

              <div
                v-for="(item, index) in order.cpItems"
                :key="index"
                class="card-header"
              >
                <div
                  class="item-name"
                  style="width: 100px;text-align: left;"
                >{{ item.CD_INFO.NAME }}</div>
                <div
                  class="item-info"
                  style="width: 80px;text-align: left;"
                >
                  <span>{{ item.CD_INFO.quantity }}</span>
                </div>
                <div
                  class="item-info"
                  style="width: 80px;text-align: right;"
                >
                  <span>¥{{ (item.CD_INFO.PRICE * item.CD_INFO.quantity).toFixed(2) }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="card-footer">
            <div v-if="['13566511216'].includes(WORKID)">
              <el-button
                type="success"
                size="large"
                circle
                @click.stop="handleComfirm(order)"
                v-if="order.STATE == '待确认'"
              >
                <el-icon>
                  <Download />
                </el-icon>
              </el-button>

              <el-button
                type="success"
                size="large"
                circle
                @click.stop="handleComfirm(order)"
                v-if="order.STATE == '已确认'"
              >
                <el-icon>
                  <Finished />
                </el-icon>
              </el-button>

              <el-popconfirm
                :title="`订单 ${order.STATE}，确定退回吗?`"
                @confirm="handleDelete(order)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="large"
                    circle
                    v-show="['待确认'].includes(order.STATE)"
                  >
                    <el-icon>
                      <DArrowLeft />
                    </el-icon>
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
            <!-- 创建人自己删除 -->
            <div v-if="[WORKID].includes(order.WORKID)">
              <el-button
                type="danger"
                size="large"
                circle
                @click.stop="handleDelete(order)"
                v-if="order.STATE == '待确认'"
              >
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </div>

            <el-button
              class="mobile-detail-btn"
              style="margin-top: 10px;"
              @click="toggleDetails(order.orderNumber)"
            >
              {{ expandedOrder === order.orderNumber ? '收起' : '详情' }}
            </el-button>
          </div>
        </el-card>
      </div>

      <div class="mobile-pagination">
        <el-button
          @click="currentPage--"
          :disabled="currentPage === 1"
        >
          上一页
        </el-button>
        <span>第 {{ currentPage }} 页</span>
        <el-button
          @click="currentPage++"
          :disabled="currentPage === totalPages"
        >
          下一页
        </el-button>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div
      v-if="deleteDialogVisible"
      class="dialog-overlay"
    >
      <div class="dialog-content">
        <h3>确认删除订单 {{ selectedOrder?.orderNumber }} 吗？</h3>
        <div class="dialog-buttons">
          <button @click="deleteDialogVisible = false">取消</button>
          <button
            @click="confirmDelete"
            class="confirm-delete"
          >确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import myAxios from '@/myAxios/myAxios';
import router from '@/router';
import { ref, computed, onMounted } from 'vue';
import VueCookie from 'vue-cookie';
import { DArrowLeft, Download, Finished, Delete } from '@element-plus/icons-vue';
import { showSuccess, showWarning } from '@/hooks/useMyMessageBox';
import myAxiosWXPost from '@/myAxios/myAxiosWXPost';

let WORKID = VueCookie.get('userid');
// let WORKID = '10659';
// 订单数据
const orders = ref([
  // {
  //   orderNumber: '20231108001',
  //   date: '2023-11-08',
  //   status: '已完成',
  //   total: 128.50,
  //   items: [
  //     { name: '宫保鸡丁', price: 38, quantity: 2 },
  //     { name: '鱼香肉丝', price: 32, quantity: 1 }
  //   ]
  // },
  // {
  //   orderNumber: '20231108002',
  //   date: '2023-11-08',
  //   status: '已完成',
  //   total: 128.50,
  //   items: [
  //     { name: '宫保鸡丁', price: 38, quantity: 2 },
  //     { name: '鱼香肉丝', price: 32, quantity: 1 }
  //   ]
  // },
  // {
  //   orderNumber: '20231108003',
  //   date: '2023-11-08',
  //   status: '已完成',
  //   total: 128.50,
  //   items: [
  //     { name: '宫保鸡丁', price: 38, quantity: 2 },
  //     { name: '鱼香肉丝', price: 32, quantity: 1 }
  //   ]
  // },
  // {
  //   orderNumber: '20231108004',
  //   date: '2023-11-08',
  //   status: '已完成',
  //   total: 128.50,
  //   items: [
  //     { name: '宫保鸡丁', price: 38, quantity: 2 },
  //     { name: '鱼香肉丝', price: 32, quantity: 1 }
  //   ]
  // },
  // 更多测试数据...
]);

// 响应式状态
const loading = ref(false);
const searchQuery = ref('');
const filterStatus = ref('');
const currentPage = ref(1);
const pageSize = 2;
const deleteDialogVisible = ref(false);
const selectedOrder = ref(null);
const expandedOrder = ref(null);
const sortKey = ref('date');
const sortOrder = ref('desc');

// 配置选项
const statusOptions = ['已完成', '进行中', '已取消'];

// 计算属性
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    const matchesSearch = order.orderNumber.includes(searchQuery.value);
    const matchesStatus = filterStatus.value ? order.status === filterStatus.value : true;
    return matchesSearch && matchesStatus;
  });
});
const statusTagType = (status) => {
  const types = {
    '待确认': 'info',
    '已退回': 'danger',
    '已确认': 'primary',
    '已完成': 'success',
  };
  return types[status] || 'info';
};

const sortedOrders = computed(() => {
  return [...filteredOrders.value].sort((a, b) => {
    const modifier = sortOrder.value === 'asc' ? 1 : -1;
    if (a[sortKey.value] > b[sortKey.value]) return 1 * modifier;
    if (a[sortKey.value] < b[sortKey.value]) return -1 * modifier;
    return 0;
  });
});

const totalPages = computed(() => Math.ceil(sortedOrders.value.length / pageSize));
const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  return sortedOrders.value.slice(start, start + pageSize);
});

// 方法
// const statusClass = (status) => {
//   return {
//     '已完成': 'completed',
//     '已确认': 'processing',
//     '未支付': 'canceled',
//   }[status] || '';
// };

const toggleDetails = (orderNumber) => {
  expandedOrder.value = expandedOrder.value === orderNumber ? null : orderNumber;
};

const handleComfirm = (order, newState) => {
  // 处理确认订单逻辑
  let state = newState;
  if (!state) {
    if (order.STATE == '待确认') {
      state = '已确认';
    }
    else if (order.STATE == '已确认') {
      state = '已完成';
    }
  }
  let param = `${order.CD_RECORD_ID}\t${state}`;
  myAxios.post(`陈帅廷更新食堂点菜记录状态`, param, '9900').then((res) => {
    if (res.includes('成功')) {
      showSuccess('提交成功!' + res);
      order.STATE = state;
      SendTemplate_WX(order, false);
    }
    else {
      showWarning('更新失败res!' + res);
    }
  });
};
const handleDelete = (order) => {
  handleComfirm(order, '已退回');
  // selectedOrder.value = order;
  // deleteDialogVisible.value = true;
};

const SendTemplate_WX = (order, isSuccess = true) => {
  // let BX_NAME = bxName(order.BX_ID);
  let RECORD_TIME = order.RECORD_TIME;
  let NAME = order.USERNAME;
  let url = `http://smart.haitian.com/Cheresting/driver_order_menu/dist/index.html#/history`
    + `?CD_RECORD_ID=${order.CD_RECORD_ID}`;
  let content = {
    'openId': 'ok-KS08CgnvAOLKnALEL142tsqYk',
    'url': url,
    'title': `${'点心外卖预约'}` + isSuccess ? '' : ' 已取消',
    'data1': `${'点心外卖预约'}` + isSuccess ? '' : ' 已取消',
    'data2': `${RECORD_TIME}`,
    'data3': `${order.WORKID} ${NAME}`,
    // 'description': '外卖订单/包厢订单',
    // 'picurl': '11',
    'remark': '请及时接收',
    'tokenname': 'ACCESS_TOKEN_WX_QDFW'
  };
  myAxiosWXPost.post(`http://192.168.100.28:85/WorkWxMsgService/WxWorkMsgService.asmx`,
    `SendTemplate_WX`, content)
    .then(pushRes => {
      // if (pushRes.includes('成功')) {
      //   let nowStr = dayjs().format('YYYY/MM/DD HH:mm:ss');
      //   myAxios.post('陈帅廷更新食堂包厢记录推送时间', `${order.BX_RECORD_ID}\t${nowStr}`);
      // }
      // console.log('pushRes :>> ', pushRes);
    });
};
const confirmDelete = () => {
  orders.value = orders.value.filter(
    o => o.orderNumber !== selectedOrder.value.orderNumber
  );
  deleteDialogVisible.value = false;
};

const toggleRowExpansion = (row) => {
  const table = document.querySelector('.el-table__body-wrapper');
  const rowElement = table.querySelector(`tr[data-id="${row.orderNumber}"]`);
  rowElement?.querySelector('.el-table__expand-icon')?.click();
};
const newCD_RECORD_ID = router.currentRoute.value.query.CD_RECORD_ID;

const tableRowClassName = ({ row, rowIndex }) => {
  if (row.BX_RECORD_ID === newCD_RECORD_ID) {
    return 'success-row';
  }
  return '';
};
const sortBy = (key) => {
  if (sortKey.value === key) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  } else {
    sortKey.value = key;
    sortOrder.value = 'asc';
  }
};

// 初始化
onMounted(() => {
  // 可以在此处添加数据加载逻辑
  let record_param = `${WORKID}`;
  if (WORKID == '13566511216') {
    record_param = ``;
  }
  myAxios.get('陈帅廷查询点菜记录', record_param, '9900').then(res => {
    // 取出所有不同的CD_RECORD_ID
    let recordIdList = res.map(item => item.CD_RECORD_ID);
    recordIdList = Array.from(new Set(recordIdList));
    // console.log('recordIdList :>> ', recordIdList);
    // 找到对应的菜品记录加到item.cpItems中
    recordIdList.forEach(recordId => {
      let cpItems = res.filter(item => item.CD_RECORD_ID === recordId);
      cpItems.forEach(item => {
        item.CD_INFO = JSON.parse(item.CD_JSON);
      });
      cpItems[0]['orderNumber'] = `${cpItems[0].WORKID}-${cpItems[0].NAME}-${cpItems[0].CREATE_TIME}`;
      cpItems[0]['cpItems'] = JSON.parse(JSON.stringify(cpItems));

    });
    let resultList = res.filter(item => item.orderNumber);
    // console.log('resultList :>> ', resultList);
    orders.value = resultList;

    if (newCD_RECORD_ID) {
      let index = orders.value.findIndex(el => el.CD_RECORD_ID === newCD_RECORD_ID);
      let page = Math.floor(index / pageSize) + 1;
      // console.log('page :>> ', page);
      currentPage.value = page > 0 ? page : 1;
    }

  });
})
</script>

<style scoped>
:deep(.warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9) !important;
}
:deep(.success-row) {
  --el-table-tr-bg-color: var(--el-color-success-light-9) !important;
}
.order-history-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 桌面端样式 */
.desktop-view {
  display: block;
}
.filter-container {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}
.order-table {
  width: 100%;
  border-collapse: collapse;
}
.order-table th,
.order-table td {
  padding: 12px;
  border-bottom: 1px solid #ddd;
  text-align: left;
}
.order-table th {
  background-color: #f8f9fa;
  cursor: pointer;
}
.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9em;
}
.completed {
  background: #e6ffed;
  color: #237804;
}
.processing {
  background: #fff7e6;
  color: #ad6800;
}
.canceled {
  background: #fff1f0;
  color: #cf1322;
}

/* 移动端样式 */
.mobile-view {
  display: none;
}
.mobile-filter {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 15px;
}
.order-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.info-row {
  display: flex;
  justify-content: space-between;
  margin: 0px 0;
}
.details {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

/* 响应式切换 */
@media (max-width: 768px) {
  .desktop-view {
    display: none;
  }
  .mobile-view {
    display: block;
  }
}

/* 通用样式 */
button {
  padding: 6px 12px;
  margin: 0 4px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}
.delete-btn,
.mobile-delete-btn {
  background: #ff4d4f;
  color: white;
  border-color: #ff4d4f;
}
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}
.dialog-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  min-width: 300px;
}
</style>